<?php

namespace app\admin\model;
use think\Db;
use think\Model;
use fast\Tree;
include_once APP_PATH . '/api/common.php';

class Apply extends Model
{
    // 表名
    public $name = 'apply_form';
    public $prefix_new = 'eb_';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    public $data;


    public function getStart_timeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['start_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setStart_timeAttr($value)
    {
        return $value && is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getEnd_timeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['end_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setEnd_timeAttr($value)
    {
        return $value && is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getAdd_timeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['add_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setAdd_timeAttr($value)
    {
        return $value && is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getCreate_timeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreate_timeAttr($value)
    {
        return $value && is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getUpdate_timeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['update_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setUpdate_timeAttr($value)
    {
        return $value && is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getDelete_timeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['delete_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setDelete_timeAttr($value)
    {
        return $value && is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getDead_timeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['dead_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setDead_timeAttr($value)
    {
        return $value && is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getTable_idTextAttr($value, $data=array())
    {
        $s=array();
        $content=[];
                if($value) {
            $nn=preg_split("/,/",$value);
        }else{
            $nn=array();
        }
        for($i=0;$i<count($nn);$i++) {
            if($nn[$i]=="") continue;
            if(isset($content[$nn[$i]])) $s[]= $content[$nn[$i]];
        }
        return join(",",$s);
    }

    public function getSchool_idTextAttr($value, $data=array())
    {
        $s=array();
        $content=[];
                if($value) {
            $nn=preg_split("/,/",$value);
        }else{
            $nn=array();
        }
        for($i=0;$i<count($nn);$i++) {
            if($nn[$i]=="") continue;
            if(isset($content[$nn[$i]])) $s[]= $content[$nn[$i]];
        }
        return join(",",$s);
    }

    public function getIs_realTextAttr($value, $data=array())
    {
        $s=array();
        $content=array(
            "0"=>"否",
            "1"=>"是",
            );
                if($value) {
            $nn=preg_split("/,/",$value);
        }else{
            $nn=array();
        }
        for($i=0;$i<count($nn);$i++) {
            if($nn[$i]=="") continue;
            if(isset($content[$nn[$i]])) $s[]= $content[$nn[$i]];
        }
        return join(",",$s);
    }

    public function getIs_closeTextAttr($value, $data=array())
    {
        $s=array();
        $content=array(
            "0"=>"未关闭",
            "1"=>"关闭",
            );
                if($value) {
            $nn=preg_split("/,/",$value);
        }else{
            $nn=array();
        }
        for($i=0;$i<count($nn);$i++) {
            if($nn[$i]=="") continue;
            if(isset($content[$nn[$i]])) $s[]= $content[$nn[$i]];
        }
        return join(",",$s);
    }

    public function getIs_openedTextAttr($value, $data=array())
    {
        $s=array();
        $content=array(
            "0"=>"未开启",
            "1"=>"已开启",
            );
                if($value) {
            $nn=preg_split("/,/",$value);
        }else{
            $nn=array();
        }
        for($i=0;$i<count($nn);$i++) {
            if($nn[$i]=="") continue;
            if(isset($content[$nn[$i]])) $s[]= $content[$nn[$i]];
        }
        return join(",",$s);
    }

    public function getIs_finishedTextAttr($value, $data=array())
    {
        $s=array();
        $content=array(
            "0"=>"未结束",
            "1"=>"已结束",
            );
                if($value) {
            $nn=preg_split("/,/",$value);
        }else{
            $nn=array();
        }
        for($i=0;$i<count($nn);$i++) {
            if($nn[$i]=="") continue;
            if(isset($content[$nn[$i]])) $s[]= $content[$nn[$i]];
        }
        return join(",",$s);
    }

    public function getIs_user_endTextAttr($value, $data=array())
    {
        $s=array();
        $content=array(
            "0"=>"否",
            "1"=>"是",
            );
                if($value) {
            $nn=preg_split("/,/",$value);
        }else{
            $nn=array();
        }
        for($i=0;$i<count($nn);$i++) {
            if($nn[$i]=="") continue;
            if(isset($content[$nn[$i]])) $s[]= $content[$nn[$i]];
        }
        return join(",",$s);
    }

    public function getIs_endTextAttr($value, $data=array())
    {
        $s=array();
        $content=array(
            "0"=>"未截止",
            "1"=>"已截止",
            );
                if($value) {
            $nn=preg_split("/,/",$value);
        }else{
            $nn=array();
        }
        for($i=0;$i<count($nn);$i++) {
            if($nn[$i]=="") continue;
            if(isset($content[$nn[$i]])) $s[]= $content[$nn[$i]];
        }
        return join(",",$s);
    }

    public function getApply_typeTextAttr($value,$data=[]){
        $status = [0 => __('预报名'), 1 => __('报名缴费'), 2 => __('报名缴费2'), 3 => __('报名+预约')];
        return isset($status[$value]) ? $status[$value] : $value;
    }

    // 课程类型文本属性
    public function getCourse_typeTextAttr($value, $data=array())
    {
        $content = array(
            "1" => "课程",
            "2" => "活动",
        );
        return isset($content[$value]) ? $content[$value] : $value;
    }

    // 报名条件开关文本属性
    public function getEnable_registration_conditionsTextAttr($value, $data=array())
    {
        $content = array(
            "0" => "关闭",
            "1" => "开启",
        );
        return isset($content[$value]) ? $content[$value] : $value;
    }

    // 分阶段报名文本属性
    public function getIs_stagedTextAttr($value, $data=array())
    {
        $content = array(
            "0" => "否",
            "1" => "是",
        );
        return isset($content[$value]) ? $content[$value] : $value;
    }

    // 阶段目标文本属性
    public function getStage1_targetTextAttr($value, $data=array())
    {
        $content = array(
            "1" => "仅预报名人群",
            "2" => "不确定人群",
            "3" => "班级人群",
        );
        return isset($content[$value]) ? $content[$value] : $value;
    }

    public function getStage2_targetTextAttr($value, $data=array())
    {
        $content = array(
            "1" => "仅预报名人群",
            "2" => "不确定人群",
            "3" => "班级人群",
        );
        return isset($content[$value]) ? $content[$value] : $value;
    }

    // 数量限制开关文本属性
    public function getEnable_quantity_limitTextAttr($value, $data=array())
    {
        $content = array(
            "0" => "关闭",
            "1" => "开启",
        );
        return isset($content[$value]) ? $content[$value] : $value;
    }

    // 每人最多可报课程数文本属性
    public function getMax_courses_per_personTextAttr($value, $data=array())
    {
        return $value ? $value . '门课程' : '无限制';
    }

    // 报名须知开关文本属性
    public function getEnable_terms_agreementTextAttr($value, $data=array())
    {
        $content = array(
            "0" => "关闭",
            "1" => "开启",
        );
        return isset($content[$value]) ? $content[$value] : $value;
    }

    // 报名表开启文本属性
    public function getEnable_registration_formTextAttr($value, $data=array())
    {
        $content = array(
            "0" => "关闭",
            "1" => "开启",
        );
        return isset($content[$value]) ? $content[$value] : $value;
    }

    // 手签板开启文本属性
    public function getEnable_signature_padTextAttr($value, $data=array())
    {
        $content = array(
            "0" => "关闭",
            "1" => "开启",
        );
        return isset($content[$value]) ? $content[$value] : $value;
    }

    // 承诺书主题文本属性
    public function getSignature_titleTextAttr($value, $data=array())
    {
        return $value ? $value : '青秀区老年大学学习活动安全承诺书';
    }

    // 承诺书正文文本属性
    public function getSignature_contentTextAttr($value, $data=array())
    {
        return $value ? $value : '本人身体健康状况良好，自愿参加青秀区老年大学的学习和活动...';
    }

    // 承诺书落款样式文本属性
    public function getSignature_footerTextAttr($value, $data=array())
    {
        return $value ? $value : '承诺人姓名：\n承诺人身份证号：\n承诺人签名：...';
    }

    // 事项设置开启文本属性
    public function getEnable_matters_settingTextAttr($value, $data=array())
    {
        $content = array(
            "0" => "关闭",
            "1" => "开启",
        );
        return isset($content[$value]) ? $content[$value] : $value;
    }

    // 课程表Excel文件路径文本属性
    public function getCourse_excel_pathTextAttr($value, $data=array())
    {
        return $value ? basename($value) : '未上传';
    }

    // 班级导入项目数据文本属性
    public function getClass_itemsTextAttr($value, $data=array())
    {
        if (empty($value)) {
            return '未设置';
        }
        $items = json_decode($value, true);
        return is_array($items) ? count($items) . '个班级项目' : '数据格式错误';
    }

    public function getTable_typeTextAttr($value, $data=array())
    {
        $s=array();
        $content=array(
            "1"=>"班级课程",
            "2"=>"教学点课程",
        );
        if($value) {
            $nn=preg_split("/,/",$value);
        }else{
            $nn=array();
        }
        for($i=0;$i<count($nn);$i++) {
            if($nn[$i]=="") continue;
            if(isset($content[$nn[$i]])) $s[]= $content[$nn[$i]];
        }
        return join(",",$s);
    }

    // 添加这个setter方法
    protected function setClass_itemsAttr($value)
    {
        if (is_array($value)) {
            // 过滤掉空的项目
            $filteredItems = [];
            foreach ($value as $item) {
                if (is_array($item) && (!empty($item['class_id']) || !empty($item['teaching_point']))) {
                    $filteredItems[] = $item;
                }
            }
            return json_encode($filteredItems, JSON_UNESCAPED_UNICODE);
        }
        return $value;
    }

    // 线下名额数量文本属性
    public function getOffline_quotaTextAttr($value, $data=array())
    {
        return $value . '人';
    }
    
    // 线下报名缴费时间限制文本属性
    public function getOffline_payment_time_limitTextAttr($value, $data=array())
    {
        return $value . '小时';
    }

    // 线下报名开启文本属性
    public function getEnable_offline_registrationTextAttr($value, $data=array())
    {
        $content = array(
            "0" => "关闭",
            "1" => "开启",
        );
        return isset($content[$value]) ? $content[$value] : $value;
    }

    // 是否使用积分文本属性
    public function getIs_use_integralTextAttr($value, $data=array())
    {
        $content = array(
            "0" => "不允许",
            "1" => "允许",
        );
        return isset($content[$value]) ? $content[$value] : $value;
    }

    // 时间字段处理方法
    public function getStage1_start_timeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['stage1_start_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setStage1_start_timeAttr($value)
    {
        return $value && is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getStage1_end_timeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['stage1_end_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setStage1_end_timeAttr($value)
    {
        return $value && is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getStage2_start_timeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['stage2_start_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setStage2_start_timeAttr($value)
    {
        return $value && is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getStage2_end_timeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['stage2_end_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setStage2_end_timeAttr($value)
    {
        return $value && is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function error($msg, $data = [], $code = 400){
        return ['code' => $code, 'msg' => $msg, 'data' => $data];
    }

    public function baoming($classes,$user){

        if (!empty($classes)) {
            $resultData=array();

            $tempUserAmount = db::name('fa_temp_user_amount')->where(['user_id'=>$user['uid']])->find();
            $amount="";
            if($tempUserAmount){
                if($tempUserAmount['classes_id']<1||$tempUserAmount['classes_id']==""||$tempUserAmount['classes_id']==null){
                    $amount=$tempUserAmount['amount'];
                }
            }

            foreach ($classes as $class) {
                if(array_key_exists('classes_id',$class)){
                    $classes_id=$class["classes_id"];
                }else{
                    $classes_id=$class[0];
                }
                if(array_key_exists('classes_type',$class)){
                    $classes_type=$class["classes_type"];
                }else{
                    $classes_type=$class[1];
                }
                $eb_classes=($classes_type==1)?'eb_classes':'fa_ocation_class';

                $alreadyApply = Db::name('eb_apply_form_item')->where(['classes_id' => $classes_id, 'user_id' => $user['uid'], 'status'=> 1,'pay_status'=>1])->order('id desc')->find();
                if ($alreadyApply) {
                    // 统计报名人数
                    $apply_num = Db::name('eb_apply_form_item')->where(['classes_id' => $classes_id,'pay_status'=>1])->count();
                    Db::name("{$eb_classes}")->where(['id' => $classes_id])->update(['apply_num' => $apply_num]);
                    if($alreadyApply['pay_status']=="1"&&$alreadyApply['order_id']) {
                        $classname = Db::name("{$eb_classes}")->where(['id' => $alreadyApply['classes_id']])->value('name');
                        return $this->error("课程【{$classname}】已经报过名,请勿重复报名!", ['classes_id' => $classes_id], 401);
                    }
                }
            }
            // 排除重复的classes_id
            $classes = array_unique($classes, SORT_REGULAR);

            foreach ($classes as $class) {
                if(array_key_exists('classes_id',$class)){
                    $classes_id=$class["classes_id"];
                }else{
                    $classes_id=$class[0];
                }
                if(array_key_exists('classes_type',$class)){
                    $classes_type=$class["classes_type"];
                }else{
                    $classes_type=$class[1];
                }
                $eb_classes=($classes_type==1)?'eb_classes':'fa_ocation_class';
                $enrollmentList = Db::name('course_table_autoplan')
                    ->alias('t')
                    ->join('fa_course_table tb', 'tb.id=t.table_id', 'Left')
                    ->join("{$eb_classes} c", 'c.id=t.classes_id', 'LEFT')
                    ->join('eb_school s', 'c.school_id=s.id', 'LEFT')
                    ->join('fa_ocation o', 'o.id=t.ocation_id', 'LEFT')
                    ->join('fa_ocation o2', 'o.pid=o2.id', 'Left')
                    ->join('(SELECT afi1.* FROM eb_apply_form_item afi1 INNER JOIN (SELECT user_id, classes_id, MAX(id) as max_id FROM eb_apply_form_item WHERE status=1 GROUP BY user_id, classes_id) afi2 ON afi1.user_id = afi2.user_id AND afi1.classes_id = afi2.classes_id AND afi1.id = afi2.max_id WHERE afi1.status=1) afi', 'afi.classes_id=c.id and afi.user_id='.$user['uid'], 'LEFT') // 只关联每个用户每个班级status=1的最后一条记录
                    ->join('eb_apply_form af', 'af.id=afi.form_id', 'LEFT')
                    ->join('fa_user u', 'u.id=afi.user_id', 'LEFT') // 新增关联
                    ->field("o.id as ocation_id,c.id,u.id as uid,tb.id as table_id,c.price,c.price as amount,c.subject_lv as subjectlv_id,c.num,c.apply_num,c.player_num,u.username,tb.name as project_name,c.id as classes_id,tb.start_date,tb.end_date,c.school_id,s.name as school_name,c.num,c.intro,c.credit_exchange,c.description,c.num-c.apply_num as remaining_slots,o2.name as ocation_name,c.name as className,c.cover,subjectlv_id_b,c.price,tb.start_date,af.id as apply_id")
                    ->where('c.id', $classes_id)
                    ->where('c.classes_type', $classes_type)
                    ->group("t.classes_id")
                    ->find();
                //Db::name('course_table_autoplan')->getLastSql()
                if($enrollmentList==null){
                    return $this->error("课程不存在!", ['classes_id' => $classes_id,'classes_type'=>$classes_type], 401);
                }

                if (isset($enrollmentList['cover'])) {
                    $enrollmentList['cover'] = preg_replace('/^https?:\/\/.*\.myqcloud\.com\//', 'https://tcimg.gxyushengwenhua.com/', $enrollmentList['cover']);
                } else {
                    $enrollmentList['cover'] = "https://tcimg.gxyushengwenhua.com/2021/09/14/1631600000_6140f1d0b1b7b.jpg";
                }

                db::execute("UPDATE eb_classes  c
                LEFT JOIN (
                    SELECT 
                        i.classes_id,
                        COUNT(1) AS apply_num_real
                    FROM eb_apply_form_item i
                    LEFT JOIN fa_order o ON o.id = i.order_id
                    WHERE o.status = 1
                      AND o.payment_status = 1
                    GROUP BY i.classes_id
                ) AS tmp ON tmp.classes_id = c.id
                SET c.apply_num = COALESCE(tmp.apply_num_real, 0)");
                $test = Db::name('eb_classes')->where(['id'=>$classes_id])->find();
                if($test['num']-$test['apply_num']<0){
                    return $this->error("课程报名人数已满{$test['num']}人! 无法再报名了！", ['classes_id' => $classes_id,'classes_type'=>$classes_type], 401);
                }

                $data = [
                    'name' => $enrollmentList['project_name']??"", // 默认名称
                    'max_num' => 0, // 默认最大人数
                    'amount' => $amount!=""?$amount:$enrollmentList['price'], // 默认金额
                    'intro' => "用户{$enrollmentList['username']}报名{$enrollmentList['className']}缴费", // 默认说明
                    'school_id' => $enrollmentList['school_id'], // 需要根据实际情况获取学校ID
                    'status' => 1, // 默认状态
                    'form_id' => $enrollmentList['table_id'], // 项目ID
                    'create_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s'),
                    'user_id' => $user['uid'], // 用户ID
                    'classes_id' => $classes_id, // 用户ID
                    'classes_type' => $classes_type, // 学校或社区
                    'teaching_ocation_id' => $enrollmentList['ocation_id'], // 教学点id
                    'school_course_classification_label_id' => $enrollmentList['subjectlv_id'], // 用户ID
                ];


                // 开启事务
                Db::startTrans();
                try {
                    // 插入报名记录
                    $result = Db::name('eb_apply_form_item')->insert($data);
                    $apply_id = Db::name('eb_apply_form_item')->getLastInsID();
                    $enrollmentList['apply_id']=$apply_id;


                    // 插入定单记录
                    if ($enrollmentList['price'] > 0) {
                        $orderData = [
                            'school_id' => $enrollmentList['school_id'],
                            'table_id' => $enrollmentList['table_id'],
                            'classes_id' => $classes_id,
                            'classes_type' => $classes_type,
                            'user_id' => $user['uid'],
                            'amount' => $amount!=""?$amount:$enrollmentList['price'],
                            'payment_status' => 0,
                            'out_trade_no' => '',
                            'create_time' => time(),
                            'update_time' => time(),
                            'delete_time' => null,
                            'status' => 0,
                            'weigh' => 0,
                            'order_sn' => 'wxpay' . date('YmdHis') . "-{$user['uid']}-{$classes_id}",
                            'apply_id' => $apply_id, // 添加报名ID到订单
                        ];
                        $order = model('Order');
                        $order->insert($orderData);
                        $orderId = $order->getLastInsID();
                        Db::name('eb_apply_form_item')->where(['id' => $apply_id])->update(['order_id' => $orderId]);
                        $enrollmentList['order_id'] = $orderId;
                        if ($orderId) {
                            $enrollmentList['OrderData'] = model('Order')->get($orderId);
                        }
                        $apply_num = Db::name('eb_apply_form_item')->where(['classes_id' => $classes_id,'classes_type'=>$classes_type])->count();
                        $apply_num++;
                        Db::name("{$eb_classes}")->where(['id' => $classes_id])->update(['apply_num' => $apply_num]);
                    }

                    // 统计报名人数
                    $apply_num = Db::name('eb_apply_form_item')->where(['classes_id' => $classes_id,'classes_type'=>$classes_type])->count();
                    Db::name("{$eb_classes}")->where(['id' => $classes_id])->update(['apply_num' => $apply_num]);

                    // 插入班级学生记录
                    $classStudentData = [
                        'classes_id' => $classes_id,
                        'classes_type' => $classes_type,
                        'student_id' => $user['uid'],
                        'add_time' => time(),
                        'status' => 0, // 默认待审核状态
                        'school_id' => $enrollmentList['school_id'], // 需要根据实际情况获取学校ID
                        'create_time' => date('Y-m-d H:i:s')
                    ];
                    Db::name('eb_class_student')->insert($classStudentData);
                    $resultData[]=array(
                        'classname'=>$enrollmentList['className']?$enrollmentList['className']:"",
                        'classes_id'=>$classes_id,
                        'classes_type'=>$classes_type,
                        'user_id'=>$user['uid'],
                        'apply_id'=>$enrollmentList['apply_id'],
                        'school_id'=>$enrollmentList['school_id'],
                        'order_sn'=>array_key_exists('OrderData',$enrollmentList) && array_key_exists('order_sn',$enrollmentList['OrderData']->toArray())?$enrollmentList['OrderData']['order_sn']:"",
                        'price'=>$amount??$enrollmentList['price'],
                        'cover'=>getImg($enrollmentList['cover'],200,200),
                        'order_id'=>array_key_exists('order_id',$enrollmentList)?$enrollmentList['order_id']:"",
                    );
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return json(['code' => 400, 'msg' => '报名失败：' . $e->getMessage()]);
                }
            }
            $message = "报名成功";
            if ($enrollmentList['price'] > 0) {
                $message = "报名成功，请及时缴费，否则名额将被释放给其他用户。";
            }
            $order_ids=[];
            foreach ($resultData as $item){
                $order_ids[]=$item['order_id'];
            }
            return json(['code' => 200, 'msg' => $message, 'data' => array("applyData"=>$resultData,"order_id"=>$order_ids)]);
        }
    }

    public function getStatusList()
    {
        return ['0' => __('失效'), '1' => __('正常')];
    }

}